<template>
  <el-dialog
    v-model="showDialog"
    title="修改分佣资格"
    class="diy-dialog-wrap"
    :destroy-on-close="true"
  >
    <el-form
      :model="formData"
      label-width="80px"
      ref="formRef"
      :rules="formRules"
      class="page-form"
      v-loading="loading"
    >
      <el-form-item label="资格开关">
        <el-radio-group v-model="formData.enabled" placeholder="请选择">
          <el-radio :label="true"> 启用 </el-radio>
          <el-radio :label="false"> 禁用 </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm(formRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { saveEnabled } from '@/api/brokerage/user'
import type { FormInstance } from 'element-plus'

const showDialog = ref(false)
const loading = ref(false)

/**
 * 表单数据
 */
const formData: Record<string, any> = reactive<any>({
  id: '',
  enabled: true
})

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
  return {
    enabled: [{ required: true, message: '请选择资格开关', trigger: 'blur' }]
  }
})

const emit = defineEmits(['complete'])

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
  if (loading.value || !formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      saveEnabled(formData)
        .then(() => {
          loading.value = false
          showDialog.value = false
          emit('complete')
        })
        .catch(() => {
          loading.value = false
        })
    }
  })
}

const setInitData = async (row: any = null) => {
  loading.value = true
  if (row) {
    formData.id = row.id
    formData.enabled = row.enabled
  }
  loading.value = false
}

defineExpose({
  showDialog,
  setInitData
})
</script>

<style lang="scss">
.diy-dialog-wrap .el-form-item__label {
  height: auto !important;
}
</style>
